package com.ysg.widget.flow;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import com.ysg.R;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * 主要用到方法
 * setData（）
 * setOnSelectListener()或 getCheckedList()
 * setMaxSelectCount()
 */
public class TagFlowLayout extends FlowLayout{
    public interface OnSelectListener {
        void onSelected(Set<Integer> selectPosSet);
    }

    private OnSelectListener mOnSelectListener;
    public void setOnSelectListener(OnSelectListener onSelectListener) {
        mOnSelectListener = onSelectListener;
    }

    //====================================================================

    private TagAdapter mTagAdapter;
    private int mSelectedMax = -1;//-1为不限制数量
    private int background, textColor;//设置背景，字体颜色
    private Set<Integer> mCheckedPositions = new HashSet();//选中的下标

    public TagFlowLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.TagFlowLayout);
        mSelectedMax = ta.getInt(R.styleable.TagFlowLayout_max_select, -1);
        background = ta.getResourceId(R.styleable.TagFlowLayout_background, 0);
        textColor = ta.getResourceId(R.styleable.TagFlowLayout_textColor, 0);
        ta.recycle();
    }

    public TagFlowLayout(Context context) {
        this(context, null);
    }

    /**
     * 设置数据：
     * 设置默认选中（position）:checkIds
     */
    public void setData(List<String> list, Set<Integer> checkIds) {
        mTagAdapter = new TagAdapter(list) {
            @Override
            public View getView(int position, String item) {
                TextView tvTitle = (TextView) LayoutInflater.from(getContext()).inflate(R.layout.item_flow_tag, null, false);
                tvTitle.setText(item);
                if (0 != background){
                    tvTitle.setBackgroundResource(background);
                }
                if (0 != textColor){
                    tvTitle.setTextColor(getResources().getColorStateList(textColor));
                }
                return tvTitle;
            }
        };
        mTagAdapter.setOnDataChangedListener(new TagAdapter.OnDataChangedListener() {
            @Override
            public void onChanged() {
                mCheckedPositions.clear();
                changeAdapter();
            }
        });
        mCheckedPositions.clear();
        mTagAdapter.setCheckedList(checkIds);
        changeAdapter();
    }

    private void changeAdapter() {
        removeAllViews();
        TagAdapter adapter = mTagAdapter;
        TagView tagViewContainer;
        HashSet checkIds = mTagAdapter.getCheckedList();
        for (int i = 0; i < adapter.getCount(); i++) {
            View tagView = adapter.getView(i, adapter.getItem(i));

            tagViewContainer = new TagView(getContext());
            tagView.setDuplicateParentStateEnabled(true);
            if (tagView.getLayoutParams() != null) {
                tagViewContainer.setLayoutParams(tagView.getLayoutParams());
            } else {
                MarginLayoutParams lp = new MarginLayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                lp.setMargins(dip2px(getContext(), 5), dip2px(getContext(), 5), dip2px(getContext(), 5), dip2px(getContext(), 5));
                tagViewContainer.setLayoutParams(lp);
            }
            LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
            tagView.setLayoutParams(lp);
            tagViewContainer.addView(tagView);
            addView(tagViewContainer);

            if (checkIds.contains(i)) {
                setChildChecked(i, tagViewContainer);
            }

            if (mTagAdapter.setSelected(i, adapter.getItem(i))) {
                setChildChecked(i, tagViewContainer);
            }
            tagView.setClickable(false);
            final TagView finalTagViewContainer = tagViewContainer;
            final int position = i;
            tagViewContainer.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    doSelect(finalTagViewContainer, position);
                }
            });
        }
        mCheckedPositions.addAll(checkIds);
    }

    /**
     * 设置最多选中的个数
     */
    public void setMaxSelectCount(int count) {
        if (mCheckedPositions.size() > count) {
            mCheckedPositions.clear();
        }
        mSelectedMax = count;
    }

    /**
     * 获取选中的下标
     */
    public Set<Integer> getCheckedList() {
        return new HashSet(mCheckedPositions);
    }

    private void setChildChecked(int position, TagView view) {
        view.setChecked(true);
        mTagAdapter.onSelected(position, view.getTagView());
    }

    private void setChildUnChecked(int position, TagView view) {
        view.setChecked(false);
        mTagAdapter.unSelected(position, view.getTagView());
    }

    private void doSelect(TagView child, int position) {
        if (!child.isChecked()) {
            //处理max_select=1的情况
            if (mSelectedMax == 1 && mCheckedPositions.size() == 1) {
                Iterator<Integer> iterator = mCheckedPositions.iterator();
                Integer preIndex = iterator.next();
                TagView pre = (TagView) getChildAt(preIndex);
                setChildUnChecked(preIndex, pre);
                setChildChecked(position, child);
                mCheckedPositions.remove(preIndex);
                mCheckedPositions.add(position);
            } else {
                if (mSelectedMax > 0 && mCheckedPositions.size() >= mSelectedMax) {
                    return;
                }
                setChildChecked(position, child);
                mCheckedPositions.add(position);
            }
        } else {
            setChildUnChecked(position, child);
            mCheckedPositions.remove(position);
        }
        if (mOnSelectListener != null) {
            mOnSelectListener.onSelected(new HashSet(mCheckedPositions));
        }
    }

    private static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}
